#include "FileTransferEntry.h"

#include "tux.h"
#include "MsnSession.h"
#include "MsnMessage.h"
#include "P2PConnection.h"


FileTransferEntry::FileTransferEntry() 
	: connection(0), message(0), file(0), fileOffset(0), fileSize(0), notifySize(0)
{
	DEBUG(_T("FileTransferEntry created"));

	notifyTime = wxDateTime::GetTimeNow();

	cancelled = false;
}

FileTransferEntry::~FileTransferEntry()
{
	DEBUG(_T("~FileTransferEntry"));

	wxDELETE(message);

	wxDELETE(file);

	wxDELETE(connection);
}

void FileTransferEntry::SetMessage(P2PMessage* msg)
{
	if(message != NULL){
		delete message;
	}

	message = msg;
}


bool FileTransferEntry::OpenFile(bool readOnly)
{
	DEBUG(_T("opening file: ")+filePath);
	file = new wxFile;

	wxFile::OpenMode mode = readOnly?wxFile::read : wxFile::write;

	if(file->Open(filePath, mode)){
		return true;
	}

	return false;
}

void FileTransferEntry::CloseFile()
{
	DEBUG(_T("closing file: ") + filePath);
	
	file->Close();

	wxDELETE(file);
}

void FileTransferEntry::WriteFileData(char* buf, int size)
{
	file->Write(buf, size);
	file->Flush();

	fileOffset += size;
}

int FileTransferEntry::ReadFileData(char* buf, int size)
{
	int actualRead = file->Read(buf, size);

	fileOffset += actualRead;

	return actualRead;
}


void FileTransferEntry::CancelTransfer()
{
	cancelled = true;

	if(connection != NULL){
		connection->Cancel();
	}else{
		session->SendP2PByeMessage(message);
	}
}

